package com.bwie.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbMenuMapper;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-06-19 14:01:26
*/
@Service
@Slf4j
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    TbMenuMapper tbMenuMapper;

    @Override
    public R adminLogin(LoginVo loginVo) {
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if(tbUser == null){
            return R.error(404,"用户不存在");
        }

        String passWord = MD5Utils.encrypt(loginVo.getUserPass());
        log.info("加密后的密码："+passWord);

        if(!tbUser.getUserPass().equals(passWord)){
            return R.error(500,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("userScore", tbUser.getUserScore())
                .compact();
        String key = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(key,token,60, TimeUnit.MINUTES);

        tbUser.setUserPass(null);
        tbUser.setToken(token);

        return R.ok(tbUser);
    }

    @Override
    public R getMenuTree() {
        String token = request.getHeader("token");
        if(token == null){
            return R.error(500,"请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);

        List<TbMenu> tbMenuList = tbMenuMapper.getMenuTree(userId);

        List<Tree<String>> treeList = TreeUtil.build(tbMenuList, "0", (menu, tree) -> {
            tree.setId(menu.getMenuId() + "");
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid() + "");
            tree.putExtra("path", menu.getMenuPath());
        });

        return R.ok(treeList);
    }

    @Override
    public R getUserList(PageInfoVo pageInfoVo) {
        Page<TbUser> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbUser> tbUserPage = tbUserMapper.selectPage(page, null);
        return R.ok(tbUserPage);
    }

    @Override
    public R getUserInfo() {
        //根据token，获取用户ID
        String token = request.getHeader("token");
        if(token == null){
            return R.error(404,"请先登录");
        }

        //根据用户ID，获取用户信息
        Integer userId = TokenUtils.getUserId(token);
        TbUser tbUser = tbUserMapper.selectById(userId);

        //根据用户ID，获取用户角色
        List<String> roleNames = tbUserMapper.getRoleNameByUserId(userId);

        StringBuilder stringBuilder = new StringBuilder();
        for (String roleName : roleNames) {
            if(stringBuilder.length()>0){
                stringBuilder.append(",").append(roleName);
            }else{
                stringBuilder.append(roleName);
            }
        }

        tbUser.setRoleNames(stringBuilder.toString());

        tbUser.setUserPass(null);

        return R.ok(tbUser);
    }

    @Override
    public R getUserInfoById(Integer userId) {
        //根据用户ID，获取用户信息
        TbUser tbUser = tbUserMapper.selectById(userId);

        if(tbUser == null){
            return R.error(404,"用户不存在");
        }

        tbUser.setUserPass(null);

        return R.ok(tbUser);
    }

    @Override
    public R signIn() {
        String token = request.getHeader("token");
        if(token == null){
            return R.error(404,"请先登录");
        }
        Integer userId = TokenUtils.getUserId(token);
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null){
            return R.error(404,"用户不存在");
        }

        int score = RandomUtil.randomInt(10, 100);
        tbUser.setUserScore(tbUser.getUserScore() + score);

        tbUserMapper.updateById(tbUser);


        return R.ok("签到成功，赠送"+score+"积分",tbUser);
    }

    @Override
    public R joinActiveSubScore(Integer userId, Integer score) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null){
            return R.error(404,"用户不存在");
        }
        if(tbUser.getUserScore()<score){
            return R.error(500,"积分不足");
        }
        tbUser.setUserScore(tbUser.getUserScore() - score);

        tbUserMapper.updateById(tbUser);
        return R.ok();
    }
}




